<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="品名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入品名" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="款号" prop="itemNum">
        <el-input v-model="queryParams.itemNum" placeholder="请输入款号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="尺码" prop="sizeNum">
        <el-input v-model="queryParams.sizeNum" placeholder="请输入尺码" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:stock:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:stock:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:stock:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" :loading="exportLoading"
          @click="handleExport" v-hasPermi="['system:stock:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="stockList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" v-if="false" />

      <el-table-column label="图片" prop="imageUrlPre">
        <template slot-scope="scope" width="90">
          <!-- <img style="width:80px;height:80px;border:none;" :src="uploadImgUrl+scope.row.imageUrlPre"> -->
          <ImagePreview style="width:120px;height:80px;border:none;" :src="scope.row.imageUrlPre" />
        </template>
      </el-table-column>
      <el-table-column label="品名" align="center" prop="name" />
      <el-table-column label="款号" align="center" prop="itemNum" />
      <el-table-column label="尺码" align="center" prop="sizeNum" />
      <el-table-column label="单价" align="center" prop="price" />
      <el-table-column label="成本" align="center" prop="cost" v-if="checkPermi(['system:stock:seeCost'])" />
      <el-table-column :label=sumLable align="center" prop="count" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCopy(scope.row)">复制</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:stock:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleReturn(scope.row)">返货</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:stock:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改库存对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item prop="imageUrlPre">
          <ImageUpload v-model="form.imageUrlPre" placeholder="上传图片" />
        </el-form-item>

        <el-form-item label="品名" prop="name">
          <el-input v-model="form.name" placeholder="请输入品名" :disabled="form.copyDisableAttribute" />
        </el-form-item>
        <el-form-item label="款号" prop="itemNum">
          <el-input v-model="form.itemNum" placeholder="请输入款号" :disabled="form.copyDisableAttribute" />
        </el-form-item>
        <el-form-item label="尺码" prop="sizeNum">
          <el-input v-model="form.sizeNum" placeholder="请输入尺码" />
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input v-model="form.price" placeholder="请输入单价" :disabled="form.copyDisableAttribute" />
        </el-form-item>
        <el-form-item label="成本" prop="cost" v-hasPermi="['system:stock:seeCost']">
          <el-input v-model="form.cost" placeholder="请输入成本" :disabled="form.copyDisableAttribute" />
        </el-form-item>
        <el-form-item label="现库存量" prop="count">
          <el-input v-model="form.count" placeholder="请输入库存量" :disabled="showAttribute" />
        </el-form-item>
        <el-form-item label="新增库存" prop="currentCount" v-if="showAttribute">
          <el-input v-model="form.currentCount" placeholder="请输入新增库存量" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addReturnstockrecord } from "@/api/system/returnstockrecord";
import { listStock, listCount, getStock, delStock, addStock, updateStock, exportStock } from "@/api/system/stock";
import { checkPermi, checkRole } from "@/utils/permission";
import moment from 'moment'
export default {
  name: "Stock",
  data() {
    return {

      //库存总数量lable
      stockSum: null,

      //隐藏属性
      showAttribute: false,
      //拷贝库存时，只允许尺码和库存的修改
      copyDisableAttribute: true,

      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存表格数据
      stockList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'id',
        isAsc: 'desc',
        name: null,
        imageUrlPre: "",
        itemNum: null,
        sizeNum: null,
        price: null,
        cost: null,
        count: null,
        currentCount: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "品名不能为空", trigger: "blur" }
        ],
        itemNum: [
          { required: true, message: "款号不能为空", trigger: "blur" }
        ],
        sizeNum: [
          { required: true, message: "尺码不能为空", trigger: "blur" }
        ],
        price: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        count: [
          { required: true, message: "库存量不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getCount();
  },

  methods: {
    checkPermi,
    checkRole,
    /** 查询库存列表 */
    getList() {
      this.loading = true;
      listStock(this.queryParams).then(response => {
        this.stockList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getCount() {
      this.loading = true;
      listCount(this.queryParams).then(response => {
        console.log(response.data);
        this.stockSum = response.data;

        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        imageUrlPre: "",
        name: null,
        itemNum: null,
        sizeNum: null,
        price: null,
        cost: null,
        count: null,
        showAttribute: false,
        copyDisableAttribute: true
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      this.getCount();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.showAttribute = false;
      this.form.copyDisableAttribute = false;
      this.open = true;
      this.title = "添加库存";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {

      this.reset();
      this.showAttribute = true;
      this.form.copyDisableAttribute = false;
      const id = row.id || this.ids
      getStock(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改库存";
      });
    },
    /** 拷贝按钮操作 */
    handleCopy(row) {
      this.reset();
      console.log(this.form);
      this.showAttribute = true;
      this.imageUrlPre = row.imageUrlPre;
      this.form.name = row.name;
      this.form.itemNum = row.itemNum;
      this.form.sizeNum = '';
      this.form.price = row.price;
      this.form.cost = row.cost;
      this.form.count = 0;
      this.open = true;
      this.title = "复制库存并修改";

    },
    //返货
    handleReturn(row) {
      console.log(row);
      this.$prompt('请输入返货数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[1-9][0-9]*$/,
        inputErrorMessage: '返货数量格式不正确'
      }).then(({ value }) => {
        if (value > row.count) {
          this.$message({
            type: 'error',
            message: '返货数量大于库存数量'
          });
          return;
        }
        const returnStock = {};
        returnStock.name = row.name;
        returnStock.imageUrlPre = row.imageUrlPre;
        returnStock.itemNum = row.itemNum;
        returnStock.sizeNum = row.sizeNum;
        returnStock.count = value;
        returnStock.effect = row.effect;
        returnStock.stockId = row.id;
        returnStock.returnDate = moment(new Date()).format('YYYY-MM-DD');

        addReturnstockrecord(returnStock).then(response => {
          this.$modal.msgSuccess("返货成功！");
          this.open = false;
          this.getList();
          this.getCount();
        });

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
        this.getList();
        this.getCount();
      });



    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateStock(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.getCount();
            });
          } else {
            addStock(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.getCount();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除库存编号为"' + ids + '"的数据项？').then(function () {
        return delStock(ids);
      }).then(() => {
        this.getList();
        this.getCount();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal.confirm('是否确认导出所有库存数据项？').then(() => {
        this.exportLoading = true;
        return exportStock(queryParams);
      }).then(response => {
        this.$download.name(response.msg);
        this.exportLoading = false;
      }).catch(() => { });
    }
  },
  computed: {
    sumLable() {
      return '库存(总件：' + this.stockSum + ')'
    }

  }
};
</script>
